import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pagewise/flutter_pagewise.dart';
import 'package:loxen/mode/inspiration/inspiration_info_bean.dart';
import 'package:loxen/mode/mine/like_list.dart';
import 'package:loxen/mode/study/study_info_bean.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/viewmode/mine_likes_viewmodel.dart';
import 'package:loxen/widget/empty_widget.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/widget/my_subassembly.dart';

class MineLikeWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<MineLikesViewModel>(
      create: (_) {
        var model = MineLikesViewModel();
        model.loadData();
        return model;
      },
      child: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size(double.infinity, 95.h),
          child: Container(
            color: Theme.of(context).backgroundColor,
            child: SafeArea(
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      MySubassembly.getBackIcon(context,
                          color: Theme.of(context).textTheme.subtitle2.color),
                      Expanded(
                        child: Center(
                          child: Text(
                            StringResources.wo_zan_guo_de,
                            style: TextStyle(
                                fontSize: 32.sp,
                                fontWeight: FontWeight.w500,
                                color: Theme.of(context).textTheme.subtitle2.color),
                          ),
                        ),
                      ),
                      MySubassembly.getSearchIcon(null, text: Text('')),
                    ],
                  )
                ],
              ),
            ),
          ),
        ),
        body: Selector<MineLikesViewModel, BaseState>(
            builder: (context, state, _) {
              if (state == BaseState.LOADING) {
                return LoadingWidget();
              }
              if (state == BaseState.CONTENT) {
                PagewiseLoadController<MineLike> pageLoadController =
                    PagewiseLoadController<MineLike>(
                        pageFuture: (page) =>
                            Provider.of<MineLikesViewModel>(context).nextData(page),
                        pageSize: 10);
                return RefreshIndicator(
                  onRefresh: () async {
                    Provider.of<MineLikesViewModel>(context, listen: false).refresh();
                    pageLoadController.reset();
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border(top: BorderSide(width: 1.h, color: Color(0xFFEBECF1))),
                      color: Theme.of(context).backgroundColor,
                    ),
                    child: PagewiseListView<MineLike>(
                        pageLoadController: pageLoadController,
                        loadingBuilder: (_) => MySubassembly.getLoadingItem(),
                        noItemsFoundBuilder: (_) => MySubassembly.getNullItem(msg: '无更多赞过的人'),
                        addAutomaticKeepAlives: false,
                        itemBuilder: (context, item, index) {
                          return GestureDetector(
                            onTap: () {
                              _detailRouter(context, item.instance_id, item.content_type);
                            },
                            child: Container(
                                color: Theme.of(context).backgroundColor,
                                margin: const EdgeInsets.only(left: 18),
                                padding: const EdgeInsets.only(top: 25, bottom: 19.5),
                                child: Row(
                                  mainAxisSize: MainAxisSize.max,
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: <Widget>[
                                    Image.network(
                                      item.cover,
                                      width: 60,
                                      height: 60,
                                      fit: BoxFit.cover,
                                    ),
                                    Expanded(
                                      child: Container(
                                        height: 60,
                                        margin: const EdgeInsets.only(left: 15, right: 18),
                                        child: Column(
                                          mainAxisSize: MainAxisSize.max,
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Text.rich(
                                              TextSpan(children: <TextSpan>[
                                                TextSpan(
                                                    text: '赞了 ',
                                                    style: TextStyle(
                                                        color: Color(0xFF999999),
                                                        fontSize: 22.sp,
                                                        height: 1)),
                                                TextSpan(
                                                    text: item.user?.nickname ?? "",
                                                    style: TextStyle(
                                                        color: Color(0xFF000000),
                                                        fontSize: 22.sp,
                                                        height: 1)),
                                                TextSpan(
                                                    text: ' 的作品',
                                                    style: TextStyle(
                                                        color: Color(0xFF999999),
                                                        fontSize: 22.sp,
                                                        height: 1)),
                                              ]),
                                              softWrap: true,
                                            ),
                                            Text(
                                              item.title.toString(),
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                  color: Color(0xFF000000),
                                                  fontSize: 28.sp,
                                                  fontWeight: FontWeight.w600,
                                                  height: 1),
                                            ),
                                            Row(
                                              children: <Widget>[
                                                GestureDetector(
                                                  onTap: () {
                                                    print('取消点赞');
//                                                _cancelLike(item.instanceId,
//                                                    item.contentType);
                                                  },
                                                  child: _createCountBar(
                                                      iconPath: 'images/like@3x.png',
                                                      count: item.like_num.toString()),
                                                ),
                                                item.content_type == 'material-product'
                                                    ? SizedBox.shrink()
                                                    : _createCountBar(
                                                        iconPath: 'images/comment@2x.png',
                                                        count: item.comment_num.toString())
                                              ],
                                            )
                                          ],
                                        ),
                                      ),
                                    ),
                                    GestureDetector(
                                      onTap: () async {
                                        bool delete = await showDeleteConfirmDialog1(context);
                                        if (delete) {
                                          context.read<MineLikesViewModel>().cancelLike(
                                              item, pageLoadController.loadedItems, onSuccess: () {
                                            pageLoadController.retry();
                                          });
                                        }
                                      },
                                      child: Container(
                                        margin: const EdgeInsets.only(right: 30.5),
                                        width: 40.w,
                                        height: 40.w,
                                        alignment: Alignment.center,
                                        decoration: BoxDecoration(
                                          image: DecorationImage(
                                            image: AssetImage('images/like_true.png'),
                                          ),
                                        ),
//                                      child: Image.asset('images/like@2x.png',
//                                          width: 11, fit: BoxFit.cover),
                                      ),
                                    )
                                  ],
                                )),
                          );
                        }),
                  ),
                );
              }

              if (state == BaseState.EMPTY) {
                return EmptyWidget();
              }
              if (state == BaseState.FAIL) {
                return FailWidget();
              }
              return Text('');
            },
            selector: (_, model) => model.mState),
      ),
    );
  }

  // 确认是否删除
  Future<bool> showDeleteConfirmDialog1(BuildContext context) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("提示"),
          content: Text(
            "您确定要取消点赞此条内容吗?",
            style: TextStyle(color: Colors.black87),
          ),
          actions: <Widget>[
            FlatButton(
              child: Text(StringResources.qu_xiao),
              onPressed: () => Navigator.of(context).pop(),
            ),
            FlatButton(
              child: Text(StringResources.shan_chu),
              onPressed: () {
                Navigator.of(context).pop(true);
              },
            ),
          ],
        );
      },
    );
  }

  Widget _createCountBar({String iconPath, String count}) {
    return Container(
      margin: const EdgeInsets.only(right: 20.5),
      child: Row(
        children: <Widget>[
          Container(
            margin: const EdgeInsets.only(right: 3),
            child: Image.asset(
              iconPath,
              width: 26.w,
              fit: BoxFit.cover,
            ),
          ),
          Text(
            count,
            style: TextStyle(
              color: Color(0xFF999999),
              fontSize: 18.sp,
              fontWeight: FontWeight.w500,
            ),
          )
        ],
      ),
    );
  }
}

// 跳转到详情
_detailRouter(BuildContext context, String id, String type) {
  switch (type) {
    case 'idea-article':
      InspirationInfo myWorks = InspirationInfo();
      myWorks.id = int.parse(id);
      Navigator.of(context).pushNamed(Routes.inspiration_detail, arguments: myWorks).then((value) {
        Provider.of<MineLikesViewModel>(context, listen: false).loadData();
      });
      break;
    case 'material-product':
      Navigator.of(context)
          .pushNamed(Routes.material_detail, arguments: int.parse(id))
          .then((value) {
        Provider.of<MineLikesViewModel>(context, listen: false).loadData();
      });
      break;
    case 'study-knowledge':
      StudyInfo entity = StudyInfo();
      entity.id = int.parse(id);
      int category = 0;
      Navigator.of(context).pushNamed(Routes.study_detail,
          arguments: {"detail": entity, "currentCategory": category}).then((value) {
        Provider.of<MineLikesViewModel>(context, listen: false).loadData();
      });
      break;
    case 'study-case':
      StudyInfo entity = StudyInfo();
      entity.id = int.parse(id);
      int category = 1;
      Navigator.of(context).pushNamed(Routes.study_detail,
          arguments: {"detail": entity, "currentCategory": category}).then((value) {
        Provider.of<MineLikesViewModel>(context, listen: false).loadData();
      });
      break;
    case 'idea-picture':
      print('跳转到灵感采集');
      break;
    default:
  }
}
